(function ($a) {
    'use strict';
    var app = $a.adminApp;
    app.controller('leiloesController.Index', function ($scope, RestFactory, $location, $localStorage, $timeout, notificationFactory, cocLoading) {

        $scope.list = [];
        $scope.orderByColumn = 'STATUS';
        $scope.reverse = false;


        var ctr = {
            api: '/api/leiloes',
            load: function () {
                cocLoading.trigger();
                var self = this;
                RestFactory.get(self.api).success(function (data) {
                    $scope.list = data;
                    $scope.currentPage = self.currentPage(); //current page
                    $scope.entryLimit = 20; //max no of items to display in a page
                    $scope.filteredItems = $scope.list.length; //Initially for no filter 
                    $scope.totalItems = $scope.list.length;
                    $timeout(function () {
                        cocLoading.trigger();
                    }, 10);
                }).error(function (data) {
                    $timeout(function () {
                        cocLoading.trigger();
                    }, 10);
                });
            },
            delete: function (id) {
                RestFactory.delete(this.api + '/' + id).success(function (data) {
                    notificationFactory.success(data.message);
                    ctr.load();
                }).error(function (data) {
                    notificationFactory.error(data.message);
                });
            },
            currentPage: function () {

                var hasPage = $localStorage.get(this.$controller);
                if (!hasPage) {
                    $localStorage.set(this.$controller, 1);
                    hasPage = 1;
                }
                return hasPage;
            },
            $controller: 'page_' + $location.$$absUrl,
            $currentPage: function (pageNo) {
                $localStorage.set(this.$controller, pageNo);
            }
        };

        ctr.load();
        $scope.setPage = function (pageNo) {
            $scope.currentPage = pageNo;
            ctr.$currentPage(pageNo);
        };
        $scope.filter = function () {
            $timeout(function () {
                $scope.filteredItems = $scope.filtered.length;
            }, 10);
        };
        $scope.resetSearch = function () {
            $scope.filteredItems = $scope.list.length;
            $scope.search = '';
        };

        $scope.orderByFnc = function (item, forceString) {
            var forceStr = forceString || false;
            if (isNaN(item[$scope.orderByColumn]) || forceString) {
                return item[$scope.orderByColumn];
            }
            return parseInt(item[$scope.orderByColumn], 10);
        };
        $scope.sort_by = function (predicate) {
            //$scope.predicate = predicate;
            $scope.orderByColumn = predicate;
            $scope.reverse = !$scope.reverse;
        };

        $scope.getStatus = function (value) {
            var status = {
                3: '<span class="label label-warning">LOTEAMENTO</span>',
                2: '<span class="label label-success">LANCE</span>',
                1: '<span class="label label-info">ANDAMENTO</span>',
                4: '<span class="label label-danger">ENCERRADO</span>',
                5: '<span class="label label-info">PROMOCIONAL</span>'
            };
            return status[value];
        };

        $scope.getTipo = function (value) {

            var xtipos = {
                EX: 'EXCLUSIVO',
                DI: 'DIRETO',
                CO: 'COMPARTILHADO',
                GR: 'AGRUPADO',
                PO: 'PROMOCIONAL'
            };
            return xtipos[value];
        };

        $scope.delete = function (id) {
            notificationFactory.confirm({
                message: 'Deseja apagar esse registro ?',
                callbackConfirm: function () {
                    ctr.delete(id);
                }
            });
        };



    });

    app.controller(
            'leilaoController.Settings',
            function ($scope, Comitentes, ApiRest, Helpers, $timeout,
                    $filter, cocGridDataFactory, RestFactory,
                    notificationFactory, $routeParams, cocLoading,
                    $location) {
                $scope.comitentes = {};
                $scope.leilao = {};
                $scope.leilao.STATUS = 3;
                $scope.leilao.ID = 0;
                $scope.Imagedata = {};
                $scope.key = $routeParams.id;
                cocLoading.trigger();
                $scope.edition = false;
                $scope.files = [];
                $scope.encerrado = false;
                $scope.leiloeiros = [];
                
                RestFactory.get('/api/leiloeiros').success(function(obj){
                    $scope.leiloeiros = obj; 
                });   
                $scope.tipos = [{
                        id: 'EX',
                        label: 'Exclusivo'
                    }, {
                        id: 'DI',
                        label: 'Direto'
                    }, {
                        id: 'CO',
                        label: 'Compartilhado'
                    },
                    {
                        id: 'PO',
                        label: 'Promocional'
                    }

                ];

                shortcut
                        .add(
                                "Ctrl+S",
                                function () {
                                    if ($scope.LeilaoForm.$valid) {
                                        $scope.save();
                                    } else {
                                        notificationFactory
                                                .error('Verifique os campos obrigatórios, esse formulário não pode ser submetido');
                                    }
                                });


                $scope.getTipo = function (key, value) {

                    var xtipos = {
                        EX: 'EXCLUSIVO',
                        DI: 'DIRETO',
                        CO: 'COMPARTILHADO',
                        GR: 'AGRUPADO',
                        PO: 'PROMOCIONAL'
                    };
                    return xtipos[value];
                };
                $scope.getDataLeilao = function () {
                    if ($scope.key > 0) {
                        cocGridDataFactory('leiloes')
                                .get(
                                        {
                                            id: $scope.key
                                        },
                                function (object) {
                                    if (object.ID === undefined) {

                                        $location
                                                .path('/leilao');
                                        return;
                                    }

                                    $scope.leilao = object;

                                    $scope.leilao.HORA = Helpers
                                            .extract(
                                                    $scope.leilao.DATA,
                                                    'time');

                                    //var
                                    // $date1 = $filter('dateFromDB')($scope.leilao.DATA, 'y-m-d H:i:s')
                                    // ;
                                    //var now = new Date();

                                    //$scope.leilao.DATA = now.getTime();
                                    var strtotime = $filter('strtotime')($scope.leilao.DATA);
                                    $scope.leilao.DATA = $filter('phpdate')('d/m/Y', strtotime);
                                    if ($scope.leilao.IMAGEM !== '') {
                                        $scope.files
                                                .push({
                                                    name: $scope.leilao.IMAGEM
                                                });
                                    }
                                    $scope.edition = true;

                                    if (parseInt(object.STATUS,
                                            10) === 4) {
                                        $scope.leilao.STATUS = parseInt(
                                                object.STATUS,
                                                10);
                                        $scope.encerrado = true;
                                    }
                                    cocLoading.trigger();
                                });
                    } else {
                        cocLoading.trigger();
                    }
                    cocGridDataFactory('comitentes').query(
                            function (ob) {
                                $scope.comitentes = ob;

                            });
                    cocGridDataFactory('condicoes').query(function (ob) {
                        $scope.condicoes = ob;
                    });

                };
                $scope.save = function ($redirect) {
                    cocLoading.trigger();
                    var $redirect = $redirect || false
                    $scope.leilao._DATA = $('input[name="DATA"]').val();
                    if ($scope.leilao.STATUS === 4) {
                        notificationFactory.error('Leilão Encerrado');
                        return;
                    }

                    $scope.leilao.IMAGEM = $('form input[name="IMAGEM"]').val();
                    // has update
                    if ($scope.key > 0) {

                        RestFactory.update('/api/leiloes', $scope.leilao)
                                .success(function (sc) {
                                    notificationFactory.success(sc.message);
                                    cocLoading.trigger();
                                    if ($redirect) {
                                        $location.path($redirect);
                                    }
                                })
                                .error(function (er) {

                                    cocLoading.trigger();
                                    notificationFactory.error(er.message);
                                });
                        return;

                    }
                    //has insert
                    RestFactory.save('/api/leiloes', $scope.leilao)
                            .success(function (sc) {
                                cocLoading.trigger();
                                notificationFactory.success(sc.message);
                                $scope.leilao = {};
                                $scope.leilao.DATA = $filter('phpdate')('d/m/Y');
                                $scope.leilao.HORA = $filter('phpdate')('H:i');
                                if ($redirect) {
                                    $location.path($redirect);
                                }
                            })
                            .error(function (er) {
                                notificationFactory.error(er.message);
                                cocLoading.trigger();
                            });


                };

                $scope.triggerButton = function () {
                    jQuery('input[onbuttonupload]').trigger('click');
                };
                $scope.uploaded = function ($data, Obj) {
                    $data = JSON.parse($data);
                    $scope.files = [];
                    $scope.files.push($data.files);

                };
                $scope.onDeleteImage = function (file) {
                    cocGridDataFactory('remove').save({
                        'ID': file,
                        'LEILAO': $scope.key
                    }, function () {
                        $scope.files = [];

                    });

                };

                $scope.onShowUserEnableds = function (obj) {

                    if ($scope.leilao.INFO.HABILITADOS > 0) {
                        cocLoading.trigger();
                        RestFactory
                                .get('/api/habilitados/' + obj.ID)
                                .success(
                                        function (response) {

                                            var $ul = '<ul class="todo-list ui-sortable">';

                                            for (var i in response.data) {
                                                var row = response.data[i];
                                                $ul += '<li><span class="text">'
                                                        + row.LOGIN
                                                        + ' - '
                                                        + row.NOME
                                                        + '</span></li>';
                                            }

                                            $ul += '</ul>';

                                            notificationFactory
                                                    .modalBox({
                                                        content: $ul,
                                                        title: "Habilitados"
                                                    });
                                            cocLoading.trigger();

                                        });
                    }

                };

                $scope.title = 'Leilao';

                $scope.optionsGridCustom = {
                    'key': 'ID',
                    'urlAdd': '#/leilao/add/',
                    'urlEdit': '#/leilao/settings/',
                    orderBy: {
                        field: 'STATUS',
                        'asc': true
                    },
                    'actions': [{
                            'url': '#/leilao/:id/lotes',
                            'label': 'preview',
                            'icon': 'fa fa-legal',
                            'title': 'Visualizar os lotes'
                        }]

                };

                $timeout(function () {
                    if (!$scope.key) {

                    }
                    $scope.getDataLeilao();

                }, 500);

            });
    app.controller('leilaoImportLotesController', [
        '$scope',
        'notificationFactory',
        '$routeParams',
        'cocGridDataFactory',
        function ($scope, notificationFactory, $routeParams,
                cocGridDataFactory) {
            $scope.process = false;

            $scope.onProgress = function (percentDone) {
                $scope.process = true;
            };
            $scope.id = $routeParams.id;
            cocGridDataFactory('leilaoFullInfo').get({
                'id': $routeParams.id
            }, function (objLeilao) {
                $scope.leilao = objLeilao;
            });

            $scope.onComplete = function (files, data, obj) {
                $scope.process = false;
                if (obj.status != 200) {
                    notificationFactory.error(data.message
                            + " <br/> Status : " + obj.status);
                } else {
                    notificationFactory.success(data.message);
                }

            };
            $scope.getLeilaoData = function () {
                return {
                    'LEILAO_ID': $routeParams.id,
                    'COMITENTE_ID': $scope.leilao.COMITENTE_ID
                };
            };
            $scope.onError = function (files, type, msg) {
                notificationFactory.error();
            };

        }]);
})(cocApp);